﻿using System;
using System.IO;
using System.Web.UI;
using BLL;
using BLL.Access;
using DevExpress.Web;
using Entity;
using Web.Class;

namespace Web.Controls.LAIHAN
{
    public partial class UCLHBtnBottom : UserControl, IUCLHOperate
    {
        void IUCLHOperate.InitControl()
        {
            throw new NotImplementedException();
        }

        public ValidateRS Validate()
        {
            throw new NotImplementedException();
        }

        public void LoadInfo(YS_LH_LAIHANXX laihanxx)
        {
            hdCollection.Set("laihanbh", laihanxx.S_LAIHANBH);
            hdCollection.Set("yonghuh", laihanxx.S_YONGHUBH);
            //this.S_YONGHUH = laihanxx.S_YONGHUBH;
            //this.S_LAIHANBH = laihanxx.S_LAIHANBH;
            //this.BtnGP.ClientEnabled = true;
            //this.BtnSC.ClientEnabled = true;
            //this.BtnWJ.ClientEnabled = true;
            if (laihanxx.I_LIUCHENGBH > 0)
            {
                DrpZLLB.Visible = false;
                BtnGP.Visible = false;
                BtnSC.Visible = false;
                UpLoadFile.Visible = false;
            }
            else
            {
                DrpZLLB.Visible = true;
                BtnGP.Visible = true;

                UpLoadFile.Visible = true;
            }
        }

        #region 属性

        /// <summary>
        ///     材料类别下拉框选中的值
        /// </summary>
        public object CAILIAOLB_SelectValue => DrpZLLB.Value;

        /// <summary>
        ///     材料类别下拉框选中的索引
        /// </summary>
        public int SelectIndex => DrpZLLB.SelectedIndex;

        public eLaiHanLX LaiHanLX
        {
            get { return (eLaiHanLX) Enum.Parse(typeof(eLaiHanLX), Convert.ToString(ViewState["LaiHanLX"])); }
            set { ViewState["LaiHanLX"] = value; }
        }

        private string needFileBH;

        private string S_YONGHUH
        {
            get { return hdCollection.Contains("yonghuh") ? Convert.ToString(hdCollection.Get("yonghuh")) : null; }
            set { hdCollection.Set("yonghuh", value); }
        }

        private string S_LAIHANBH
        {
            get { return hdCollection.Contains("laihanbh") ? Convert.ToString(hdCollection.Get("laihanbh")) : null; }
            set { hdCollection.Set("laihanbh", value); }
        }
        public int lhFlag = 0;
        #endregion

        #region 变量

        /// <summary>
        ///     访问数据库
        /// </summary>
        private readonly SpHelper _sphelper = new SpHelper();

        /// <summary>
        ///     上传文件信息BLL
        /// </summary>
        private readonly SYS_UPLOADProcess bllupload = new SYS_UPLOADProcess();

        private readonly SYS_UPLOAD_LOGBLL uploadLOGBLL = new SYS_UPLOAD_LOGBLL();

        #endregion

        #region 事件

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) InitControl();
            needFileBH = LaiHanLCTools.GetNeedFileBH((int) LaiHanLX);
        }

        protected void UCLHBtnBottom_ASPxCallbackCommon_Callback(object source, CallbackEventArgs e)
        {
            if (e.Parameter == "session")
            {
                Session["LB"] = DrpZLLB.Text;
                Session["LBID"] = DrpZLLB.Value.ToString();
                e.Result = Session["LB"] + Session["LBID"].ToString();
            }
        }

        protected void uplImage_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            e.CallbackData = SavePostedFile(e.UploadedFile);
        }

        protected void DrpZLLB_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["LB"] = DrpZLLB.Text;
            Session["LBID"] = DrpZLLB.Value.ToString();
        }

        #endregion

        #region 方法

        public ValidateRS ValidateSubmit(string laihanbh, string yonghuh)
        {
            var rs = new ValidateRS();
            var where = "";
            //where = string.Format(" S_YONGHUBH='{0}' and  I_WENJIANLX={2} and S_LAIHANBH='{1}' and I_JLZT=0 ", yonghuh, laihanbh, this.needFileBH);
            //where = string.Format("  I_WENJIANLX={2} and (S_LAIHANBH='{0}' or (S_LAIHANBH IS NULL AND S_YONGHUBH={1})) and I_JLZT=0 ", laihanbh, yonghuh, this.needFileBH);
            where = string.Format("  S_YONGHUBH='{0}' and I_WENJIANLX={1} and I_JLZT=0 AND S_LAIHANBH IS NULL", yonghuh,
                needFileBH);
            var dt = bllupload.SelectSYS_UPLOADsDynamic(where, "", null);
            if (dt != null && dt.Rows.Count > 0)
            {
                rs.IsSuccess = true;
                return rs;
            }

            rs.Msg = "申请来函未上传";
            return rs;
        }

        /// <summary>
        ///     更新来涵文件信息
        /// </summary>
        /// <param name="laihan">来函信息</param>
        public void SHOUJIAN(YS_LH_LAIHANXX laihan)
        {
            var upload = new SYS_UPLOAD();
            var count = bllupload.UpdateSYS_UPLOADsDynamic(
                "S_LAIHANBH='" + laihan.S_LAIHANBH + "',S_CAOZUOR='" + LoginInfo.CurrentUser.UserID +
                "',D_CAOZUORQ=TO_DATE('" + DateTime.Now + "','yyyy-MM-dd HH24:mi:ss'),I_TYPE=" + BusinessTool.WType,
                string.Format(" S_YONGHUBH='{0}' and I_WENJIANLX in ({1}) and S_LAIHANBH IS NULL", laihan.S_YONGHUBH,
                    needFileBH));
            /*comment by guodengjie at 2017-10-31
            string yd = BusinessTool.YS_GETSETTINGSVALUE(eSETTINGS_KEYNAME.WATER_Y_M.ToString());
            int year = Convert.ToInt32(yd.Substring(0, 4));
            int month = int.Parse(yd.Substring(4, 2));
            SYS_UPLOAD upload = new SYS_UPLOAD();
            upload.I_SUOSHUMK = 1;
            upload.I_TYPE = 1;
            upload.S_CAOZUOR = LoginInfo.CurrentUser.Account;
            upload.S_LAIHANBH = laihan.S_LAIHANBH;
            upload.S_YONGHUBH = laihan.S_YONGHUBH;
            upload.D_CAOZUORQ = DateTime.Now;
            if (Session["gaopai"] != null)
            {
                DataTable uploadtable = Session["gaopai"] as DataTable;
                foreach (DataRow dr in uploadtable.Rows)
                {
                    upload.ID = 0;
                    ///证件类型的文件只和用户相关，更新
                    if (dr["value"].ToString() != needFileBH)
                    {
                        DataTable shangchuan = bllupload.SelectSYS_UPLOADsDynamic(string.Format(" S_YONGHUBH='{0}' and I_WENJIANLX={1} ", laihan.S_YONGHUBH, dr["value"]), "", null);
                        if (shangchuan != null && shangchuan.Rows.Count > 0)
                        {
                            upload.ID = Convert.ToInt32(shangchuan.Rows[0]["ID"]);
                        }
                    }
                    upload.S_WENJIANMC = dr["name"].ToString();
                    upload.S_WENJIANLJ = dr["path"].ToString();
                    upload.I_WENJIANLX = Convert.ToInt32(dr["value"]);
                    upload.I_SHANGCHUANLB = Convert.ToInt32(dr["type"]);
                    bllupload.InsertOrUpdate(upload);

                    SYS_UPLOAD_LOG uploadlog = new SYS_UPLOAD_LOG();
                    uploadlog.D_CAOZUORQ = DateTime.Now;
                    uploadlog.I_CAOZUOR = LoginInfo.CurrentUser.UserID;
                    uploadlog.I_JLZT = 0;
                    uploadlog.I_TYPE = 1;
                    uploadlog.I_WENJIANLX = Convert.ToInt32(dr["value"]);
                    uploadlog.ID = 0;
                    uploadlog.S_WENJIANLJ = dr["path"].ToString();
                    uploadlog.S_WENJIANMC = dr["name"].ToString();
                    uploadlog.S_YONGHUBH = laihan.S_YONGHUBH;
                    new SYS_LOGBLL().Log<SYS_UPLOAD>(LoginInfo.CurrentUser, BusinessTool.WType.ToString(), "来函处理" + laihan.I_LAIHANLX, OperateState.Modify, upload, null);
                    uploadLOGBLL.InsertOrUpdate(uploadlog);


                    Session["gaopai"] = null;
                }
            }
             * */
        }

        private string SavePostedFile(UploadedFile uploadedFile)
        {
            var uploadDirectory = PageTools.GetUploadPath(BusinessTool.WType, "lh");
            if (!uploadedFile.IsValid) return string.Empty;
            var fileName = Guid.NewGuid() + Path.GetExtension(uploadedFile.FileName); //文件名
            var filePath = Path.Combine(Server.MapPath(uploadDirectory), fileName); //文件完整物理路径
            uploadedFile.SaveAs(filePath);
            //存入数据库
            var uploadlog = new SYS_UPLOAD_LOG();
            uploadlog.D_CAOZUORQ = DateTime.Now;
            uploadlog.I_CAOZUOR = LoginInfo.CurrentUser.UserID;
            uploadlog.I_JLZT = 0;
            uploadlog.I_TYPE = BusinessTool.WType;
            uploadlog.I_WENJIANLX = Convert.ToInt32(Session["LBID"]);
            uploadlog.ID = 0;
            uploadlog.S_WENJIANLJ = Path.Combine(uploadDirectory, fileName);
            uploadlog.S_WENJIANMC = Convert.ToString(Session["LB"]);
            uploadlog.S_YONGHUBH = S_YONGHUH;
            uploadLOGBLL.InsertOrUpdate(uploadlog);
            var upload = new SYS_UPLOAD();
            upload.I_JLZT = 0;
            upload.D_CAOZUORQ = uploadlog.D_CAOZUORQ;
            upload.S_CAOZUOR = uploadlog.I_CAOZUOR.ToString();
            upload.I_TYPE = BusinessTool.WType;
            upload.I_WENJIANLX = uploadlog.I_WENJIANLX;
            //如果为申请表,同一用户同一类型尚未有来函编号的 最多只存在一个
            needFileBH = LaiHanLCTools.GetNeedFileBH((int) LaiHanLX);
            var where = "";
            int index = Array.IndexOf(needFileBH.Split(','), upload.I_WENJIANLX.ToString());
            if (index >= 0)//upload.I_WENJIANLX == decimal.Parse(needFileBH)
            {
                where = "I_JLZT=0 AND S_YONGHUBH='" + S_YONGHUH + "' AND I_WENJIANLX=" + upload.I_WENJIANLX +
                        (!string.IsNullOrEmpty(S_LAIHANBH)
                            ? " AND S_LAIHANBH='" + S_LAIHANBH + "'"
                            : " AND S_LAIHANBH IS NULL");
                upload.S_LAIHANBH = S_LAIHANBH;
            }
            else
            {
                where = "I_JLZT=0 AND S_YONGHUBH='" + S_YONGHUH + "' AND I_WENJIANLX=" + upload.I_WENJIANLX + " AND S_LAIHANBH IS NULL";
            }

            var shangchuan = bllupload.SelectSYS_UPLOADsDynamic(where, "", null);
            if (shangchuan != null && shangchuan.Rows.Count > 0) upload.ID = Convert.ToInt32(shangchuan.Rows[0]["ID"]);
            upload.S_WENJIANLJ = uploadlog.S_WENJIANLJ;
            upload.S_WENJIANMC = uploadlog.S_WENJIANMC;
            upload.S_YONGHUBH = uploadlog.S_YONGHUBH;
            upload.I_SHANGCHUANLB = 1; //普通上传
            upload.I_SUOSHUMK = 1; //来函
            bllupload.InsertOrUpdate(upload);
            /* comment by guodengjie at 20170921 19:39
            if (Session["gaopai"] != null)
            {
                DataTable dt = Session["gaopai"] as DataTable;
                DataRow dr = dt.NewRow();
                dr[0] = uploadDirectory + fileName;
                dr[1] = dt.Rows.Count + 1;
                dr[2] = Session["LB"];
                dr[3] = Session["LBID"];
                dr[4] = 1;
                dt.Rows.Add(dr);
                Session["gaopai"] = dt;
            }
            else
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("path");
                dt.Columns.Add("rownum");
                dt.Columns.Add("name");
                dt.Columns.Add("value");
                dt.Columns.Add("type");
                DataRow dr = dt.NewRow();
                dr[0] = uploadDirectory + fileName;
                dr[1] = dt.Rows.Count + 1;
                dr[2] = Session["LB"];
                dr[3] = Session["LBID"];
                dr[4] = 1;
                dt.Rows.Add(dr);
                Session["gaopai"] = dt;
            }
            */
            return filePath; //返回文件名用于预览
        }

        private void InitControl()
        {
            hdCollection.Set("wtype", BusinessTool.WType);
            hdCollection.Set("laihanlx", (int) LaiHanLX);
            //this.BtnGP.ClientEnabled = false;
            //this.BtnSC.ClientEnabled = false;
            //this.BtnWJ.ClientEnabled = false;
            var ds = _sphelper.P_YS_LH_LAIHANZLLB((int) LaiHanLX);
            var dt = ds.Tables[0];

            DrpZLLB.DataSource = ds.Tables[0];
            DrpZLLB.TextField = "S_CAILIAOMC";
            DrpZLLB.ValueField = "I_CAILIAOBH";
            DrpZLLB.DataBind();
            DrpZLLB.SelectedIndex = 0;
            if (dt.Rows.Count > 0)
            {
                Session["LBID"] = ds.Tables[0].Rows[0]["I_CAILIAOBH"];
                Session["LB"] = ds.Tables[0].Rows[0]["S_CAILIAOMC"];
            }

            Session["gaopai"] = null;

            //if (lhFlag == 1)
            //{
            //    BtnWJ.Visible = false;
            //}
        }


        public void ClearInfo()
        {
            Session["gaopai"] = null;
            Session["LBID"] = null;
            Session["LB"] = null;
        }

        #endregion
    }
}